package com.lijinjiang.controller.impl;

import com.lijinjiang.controller.PropertiesHandler;
import com.lijinjiang.model.tree.ServerConnection;
import com.lijinjiang.util.FileUtil;

import java.io.File;
import java.util.*;

/**
 * @ClassName PropertiesHandlerImpl
 * @Description 属性文件处理类
 * @Author Li
 * @Date 2022/8/15 14:15
 * @ModifyDate 2022/8/15 14:15
 * @Version 1.0
 */
public class PropertiesHandlerImpl implements PropertiesHandler {
    /**
     * 保存服务器连接
     * @param sc
     */
    @Override
    public void saveSC(ServerConnection sc) {
        // 创建配置文件名，这些 properties 文件存放于 profile 目录下
        String scProfileName = FileUtil.SC_PATH + sc.getName() + ".properties";
        // 创建 properties 文件
        File scProfile = new File(scProfileName);
        // 写入流信息
        FileUtil.createProfile(scProfile);
        Properties prop = new Properties();
        prop.setProperty(FileUtil.HOST, sc.getHost());
        prop.setProperty(FileUtil.PORT, sc.getPort());
        prop.setProperty(FileUtil.USER, sc.getUser());
        prop.setProperty(FileUtil.PASSWORD, sc.getPassword());
        FileUtil.saveProperties(scProfile, prop, "ServerConnection " + sc.getName() + " config.");

    }


    /**
     * 按序获取所有的连接配置
     * @return
     */
    @Override
    public List<ServerConnection> getAllSC() {
        File filePath = new File(FileUtil.SC_PATH); // 获取配置文件存储位置
        File[] profiles = filePath.listFiles(); // 获取所有的连接配置文件
        List<ServerConnection> list = new ArrayList<>();
        for (File profile : profiles) {
            ServerConnection sc = getServerConnectionFromFile(profile);
            list.add(sc);
        }
        return list;
    }

    /**
     * 根据连接文件获取配置信息
     * @param profile
     * @return
     */
    private ServerConnection getServerConnectionFromFile(File profile) {
        try {
            Properties pro = FileUtil.getProperties(profile);
            ServerConnection SConnection = new ServerConnection(FileUtil.getFileName(profile),
                    pro.getProperty(FileUtil.HOST),
                    pro.getProperty(FileUtil.PORT),
                    pro.getProperty(FileUtil.USER),
                    pro.getProperty(FileUtil.PASSWORD));
            return SConnection;
        } catch (Exception e) {
            throw new RuntimeException("读取配置文件错误！");
        }
    }
}
